using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Colman.Rpg.Messaging;
using Colman.Rpg.Connection;

namespace Colman.Rpg
{
    /// <summary>
    /// A base form with awareness to incoming messages.
    /// </summary>
    public class ConnectionAwareForm : Form
    {
        /// <summary>
        /// Creates a new instance of <see cref="ConnectionAwareForm" />.
        /// </summary>
        public ConnectionAwareForm()
        {
            this.Icon = Colman.Rpg.Properties.Resources.RpgIcon;
        }

        /// <summary>
        /// Raises the <see cref="Form.Load" /> event.
        /// </summary>
        /// <param name="e">An <see cref="EventArgs" /> that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!this.DesignMode)
            {
                ClientEndPoint.Instance.MessageReceived += this.Form_MessageReceived;
            }
        }

        /// <summary>
        /// Raises the <see cref="Form.Closed" /> event.
        /// </summary>
        /// <param name="e">An <see cref="EventArgs" /> that contains the event data.</param>
        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);

            if (!this.DesignMode)
            {
                ClientEndPoint.Instance.MessageReceived -= this.Form_MessageReceived;
            }
        }

        private void Form_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new EventHandler<MessageReceivedEventArgs>(this.Form_MessageReceived), sender, e);
            }
            else
            {
                this.OnMessageReceived(sender, e);
            }
        }

        /// <summary>
        /// Called when a message is received from the server.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">The message arguments.</param>
        protected virtual void OnMessageReceived(object sender, MessageReceivedEventArgs e)
        {
            if (e.Message is ServerShutdownResponse)
            {
                MessageBox.Show(this, "The server has unexpectedly shut down. The game can not proceed and will close.",
                    this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();
            // 
            // ConnectionAwareForm
            // 
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Name = "ConnectionAwareForm";
            this.ResumeLayout(false);

        }
    }
}